<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeMenu = ref(router.currentRoute.value.path)
const collapsed = ref(false)
const isFullscreen = ref(false)

const menuItems = [
  { path: '/', label: '首页', icon: 'fa-solid fa-home' },
  { path: '/products', label: '商品列表', icon: 'fa-solid fa-list' },
  { path: '/system/add-admin', label: '添加管理员', icon: 'fa-solid fa-user-plus' },
  { path: '/group-buying', label: '拼团列表', icon: 'fa-solid fa-users-line' },
  { path: '/orders', label: '订单管理', icon: 'fa-solid fa-shopping-cart' },
  { path: '/users', label: '用户管理', icon: 'fa-solid fa-users' },
  { path: '/system', label: '系统设置', icon: 'fa-solid fa-cog' }
  
]

const handleMenuClick = (path) => {
  activeMenu.value = path
  router.push(path)
  // 添加标签
  addTag({
    path,
    meta: { title: menuItems.find(item => item.path === path)?.label }
  })
}

// 切换全屏
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
    isFullscreen.value = true
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen()
      isFullscreen.value = false
    }
  }
}

// 监听全屏变化
document.addEventListener('fullscreenchange', () => {
  isFullscreen.value = !!document.fullscreenElement
})

// 添加标签导航数据
const visitedTags = ref([
  { path: '/', title: '首页', closable: false },
  { path: '/orders', title: '订单管理', closable: true },
  { path: '/users', title: '用户管理', closable: true }
])

// 关闭标签
const closeTag = (targetPath) => {
  const index = visitedTags.value.findIndex(tag => tag.path === targetPath)
  if (index > -1) {
    visitedTags.value.splice(index, 1)
    // 如果关闭的是当前页面，则跳转到前一个标签
    if (targetPath === router.currentRoute.value.path) {
      const prevTag = visitedTags.value[index - 1] || visitedTags.value[0]
      router.push(prevTag.path)
      // 更新左侧菜单激活状态
      activeMenu.value = prevTag.path
    }
  }
}

// 添加标签
const addTag = (route) => {
  const isExist = visitedTags.value.some(tag => tag.path === route.path)
  if (!isExist) {
    visitedTags.value.push({
      path: route.path,
      title: route.meta.title || menuItems.find(item => item.path === route.path)?.label,
      closable: route.path !== '/'
    })
  }
  // 更新左侧菜单激活状态
  activeMenu.value = route.path
}

// 监听路由变化
watch(() => router.currentRoute.value, (newRoute) => {
  if (newRoute.name) {
    addTag(newRoute)
    // 同步更新左侧菜单激活状态
    activeMenu.value = newRoute.path
  }
}, { immediate: true })

// 添加右键菜单相关状态
const contextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
  targetPath: ''
})

// 显示右键菜单
const showContextMenu = (e, tag) => {
  e.preventDefault()
  contextMenu.value = {
    visible: true,
    x: e.clientX,
    y: e.clientY,
    targetPath: tag.path
  }
}

// 关闭右键菜单
const closeContextMenu = () => {
  contextMenu.value.visible = false
}

// 关闭其他标签
const closeOtherTags = () => {
  visitedTags.value = visitedTags.value.filter(tag => 
    tag.path === contextMenu.value.targetPath || !tag.closable
  )
  closeContextMenu()
}

// 关闭所有可关闭的标签
const closeAllTags = () => {
  visitedTags.value = visitedTags.value.filter(tag => !tag.closable)
  router.push('/')
  activeMenu.value = '/'
  closeContextMenu()
}

// 监听全局点击事件关闭右键菜单
onMounted(() => {
  document.addEventListener('click', closeContextMenu)
})

onUnmounted(() => {
  document.removeEventListener('click', closeContextMenu)
})

// 添加登出方法
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  router.push('/login')
}

// 添加用户菜单控制
const showUserMenu = ref(false)

// 切换用户菜单显示状态
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value
}

// 关闭用户菜单
const closeUserMenu = () => {
  showUserMenu.value = false
}

// 修改密码
const showPasswordModal = ref(false)
const passwordLoading = ref(false)
const passwordError = ref('')
const passwordSuccess = ref('')

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 打开修改密码弹窗
const handleChangePassword = () => {
  showPasswordModal.value = true
  closeUserMenu()
}

// 关闭修改密码弹窗
const closePasswordModal = () => {
  showPasswordModal.value = false
  passwordError.value = ''
  passwordSuccess.value = ''
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

// 提交修改密码
const submitPasswordChange = async () => {
  // 表单验证
  if (!passwordForm.value.oldPassword) {
    passwordError.value = '请输入原密码'
    return
  }
  if (!passwordForm.value.newPassword) {
    passwordError.value = '请输入新密码'
    return
  }
  if (passwordForm.value.newPassword.length < 6) {
    passwordError.value = '新密码长度不能少于6位'
    return
  }
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    passwordError.value = '两次输入的密码不一致'
    return
  }

  try {
    passwordLoading.value = true
    passwordError.value = ''
    passwordSuccess.value = ''

    const response = await fetch('http://localhost:3001/api/admin/change-password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({
        oldPassword: passwordForm.value.oldPassword,
        newPassword: passwordForm.value.newPassword
      })
    })

    const data = await response.json()

    if (response.ok) {
      passwordSuccess.value = '密码修改成功'
      // 3秒后关闭弹窗
      setTimeout(() => {
        closePasswordModal()
      }, 3000)
    } else {
      passwordError.value = data.message || '密码修改失败'
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    passwordError.value = '服务器错误，请稍后重试'
  } finally {
    passwordLoading.value = false
  }
}

// 监听全局点击事件关闭用户菜单
onMounted(() => {
  document.addEventListener('click', closeUserMenu)
})

onUnmounted(() => {
  document.removeEventListener('click', closeUserMenu)
})
</script>

<template>
  <div class="layout">
    <aside class="sidebar" :class="{ collapsed }">
      <div class="logo">
        <h1 v-show="!collapsed">社区团购管理系统</h1>
        <button class="collapse-btn" @click="collapsed = !collapsed">
          {{ collapsed ? '>' : '<' }}
        </button>
      </div>
      <nav class="menu">
        <div
          v-for="item in menuItems"
          :key="item.path"
          class="menu-item"
          :class="{ active: activeMenu === item.path }"
          @click="handleMenuClick(item.path)"
        >
          <i :class="item.icon"></i>
          <span v-show="!collapsed">{{ item.label }}</span>
        </div>
      </nav>
    </aside>
    
    <div class="main-container">
      <header class="header">
        <div class="header-left">
          <h2>{{ $route.meta.title }}</h2>
        </div>
        <div class="header-right">
          <button class="header-btn" @click="toggleFullscreen">
            <i :class="isFullscreen ? 'fa-solid fa-compress' : 'fa-solid fa-expand'"></i>
            {{ isFullscreen ? '退出全屏' : '全屏' }}
          </button>
          <span class="divider"></span>
          <div class="user-dropdown" @click.stop>
            <span class="user-info" @click="toggleUserMenu">
              <i class="fa-solid fa-user"></i>
              管理员
              <i class="fa-solid fa-chevron-down" :class="{ 'rotate': showUserMenu }"></i>
            </span>
            <!-- 用户菜单 -->
            <div class="user-menu" v-show="showUserMenu">
              <div class="user-menu-item" @click="handleChangePassword">
                <i class="fa-solid fa-key"></i>
                修改密码
              </div>
              <div class="user-menu-item" @click="handleLogout">
                <i class="fa-solid fa-right-from-bracket"></i>
                退出登录
              </div>
            </div>
          </div>
        </div>
      </header>

      <!-- 添加标签导航 -->
      <div class="tags-nav">
        <div class="tags-wrapper">
          <router-link
            v-for="tag in visitedTags"
            :key="tag.path"
            :to="tag.path"
            class="tag-item"
            :class="{ active: $route.path === tag.path }"
            @contextmenu.prevent="showContextMenu($event, tag)"
          >
            {{ tag.title }}
            <i 
              v-if="tag.closable" 
              class="fa-solid fa-xmark tag-close"
              @click.prevent="closeTag(tag.path)"
            ></i>
          </router-link>
        </div>
      </div>

      <!-- 添加右键菜单 -->
      <div 
        v-show="contextMenu.visible"
        class="context-menu"
        :style="{
          left: contextMenu.x + 'px',
          top: contextMenu.y + 'px'
        }"
      >
        <div class="context-menu-item" @click="closeOtherTags">
          关闭其他标签
        </div>
        <div class="context-menu-item" @click="closeAllTags">
          关闭所有标签
        </div>
      </div>

      <main class="main-content">
        <div class="content-wrapper">
          <router-view></router-view>
        </div>
      </main>
    </div>

    <!-- 修改密码弹窗 -->
    <div v-if="showPasswordModal" class="modal-overlay" @click="closePasswordModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>修改密码</h3>
          <button class="close-btn" @click="closePasswordModal">
            <i class="fa-solid fa-times"></i>
          </button>
        </div>

        <form @submit.prevent="submitPasswordChange" class="modal-form">
          <div class="form-group">
            <label>原密码</label>
            <input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入原密码"
              required
            >
          </div>

          <div class="form-group">
            <label>新密码</label>
            <input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              required
            >
            <div class="form-tip">密码长度不少于6位</div>
          </div>

          <div class="form-group">
            <label>确认新密码</label>
            <input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              required
            >
          </div>

          <div v-if="passwordError" class="error-message">
            <i class="fa-solid fa-circle-exclamation"></i>
            {{ passwordError }}
          </div>

          <div v-if="passwordSuccess" class="success-message">
            <i class="fa-solid fa-circle-check"></i>
            {{ passwordSuccess }}
          </div>

          <div class="modal-footer">
            <button type="button" class="cancel-btn" @click="closePasswordModal">取消</button>
            <button type="submit" :disabled="passwordLoading" class="submit-btn">
              {{ passwordLoading ? '提交中...' : '确认修改' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.layout {
  display: flex;
  min-height: 100vh;
  background-color: var(--bg-color-secondary);
  color: var(--text-color);
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.sidebar {
  width: 256px;
  background-color: var(--bg-color);
  color: var(--text-color);
  border-right: 1px solid var(--border-color);
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
}

.sidebar.collapsed {
  width: 80px;
}

.logo {
  height: 64px;
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid var(--border-color);
}

.logo h1 {
  font-size: 18px;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.collapse-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  color: var(--primary-color);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  font-weight: bold;
  font-size: 16px;
  outline: none;
}

.collapse-btn:focus {
  outline: none;
}

.collapse-btn i {
  font-size: 16px;
  transition: transform 0.3s;
}

.sidebar.collapsed .collapse-btn i {
  transform: rotate(180deg);
}

.menu {
  flex: 1;
  padding: 16px 0;
}

.menu-item {
  padding: 12px 24px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 4px 16px;
  border-radius: var(--border-radius);
  color: var(--text-color);
  background: transparent;
}

.menu-item:hover {
  background-color: var(--primary-color);
  opacity: 0.8;
  color: white;
}

.menu-item.active {
  background-color: var(--primary-color);
  color: white;
  box-shadow: 0 2px 8px rgba(var(--primary-color-rgb), 0.3);
}

.icon {
  font-size: 18px;
  width: 24px;
  text-align: center;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.header {
  height: 64px;
  background: var(--bg-color);
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  border-bottom: 1px solid var(--border-color);
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-btn {
  padding: 4px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.header-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.divider {
  width: 1px;
  height: 24px;
  background: #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
}

.user-info:hover {
  background: rgba(0,0,0,0.025);
}

.main-content {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: var(--bg-color-secondary);
  position: absolute;
  top: 104px;
  left: 0;
  right: 0;
  bottom: 0;
}

.content-wrapper {
  height: 100%;
  padding: 0 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    height: 100vh;
    z-index: 1000;
    transform: translateX(0);
  }

  .sidebar.collapsed {
    transform: translateX(-100%);
  }

  .main-container {
    margin-left: 0;
  }
}

/* 全屏时的样式 */
:fullscreen .layout {
  background: var(--bg-color-secondary);
}

:fullscreen .main-container {
  height: 100vh;
}

/* 调整应式布局 */
@media (max-width: 1600px) {
  .content-wrapper {
    margin: 0 24px;
  }
}

@media (max-width: 1200px) {
  .main-container {
    min-width: auto;
  }
  
  .content-wrapper {
    min-width: auto;
  }
}

.main-container,
.content-wrapper {
  min-width: auto;
  max-width: none;
  margin: 0;
}

.tags-nav {
  height: 40px;
  background: var(--bg-color);
  padding: 0 16px;
  position: relative;
  z-index: 10;
  border-top: none;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.tags-wrapper {
  height: 100%;
  display: flex;
  align-items: center;
  gap: 8px;
  overflow-x: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.tags-wrapper::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.tag-item {
  height: 32px;
  line-height: 32px;
  padding: 0 12px;
  background: transparent;
  color: var(--text-color-secondary);
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s;
  white-space: nowrap;
  position: relative;
  border-radius: var(--border-radius);
}

.tag-item:hover {
  color: var(--primary-color);
  background: transparent;
}

.tag-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 2px;
  background: var(--primary-color);
  transition: all 0.3s;
  opacity: 0;
  transform: translateX(-50%);
}

.tag-item:hover::after {
  width: 100%;
  opacity: 0.5;
}

.tag-item.active {
  color: var(--primary-color);
  background: var(--primary-color);
  background: rgba(var(--primary-color-rgb), 0.1);
}

.tag-item.active::after {
  width: 100%;
  opacity: 1;
}

.tag-close {
  font-size: 12px;
  margin-left: 4px;
  cursor: pointer;
  transition: all 0.3s;
  color: var(--text-color-secondary);
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tag-item:not(.active) .tag-close:hover {
  color: var(--error-color);
}

.tag-item.active .tag-close:hover {
  color: var(--error-color);
}

/* 美化用户信息区域 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.3s;
  color: var(--text-color);
}

.user-info:hover {
  background: rgba(0,0,0,0.04);
}

.icon {
  font-size: 16px;
}

.arrow-icon {
  font-size: 12px;
  color: #999;
}

/* 调整主内容区域的位置 */
.main-content {
  top: 104px; /* header + tags-nav 的高度 */
}

/* 美化滚动条 */
.main-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.main-content::-webkit-scrollbar-thumb {
  background: var(--border-color);
}

.main-content::-webkit-scrollbar-track {
  background: var(--bg-color-secondary);
}

/* ��化按钮 */
.header-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  height: 32px;
  padding: 0 16px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  background: var(--bg-color);
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.3s;
}

.header-btn:hover {
  color: var(--primary-color);
  border-color: var(--primary-color);
  background: #f0f7ff;
}

/* 调整图标样式 */
.menu-item i {
  width: 20px;
  text-align: center;
  margin-right: 8px;
}

.user-info i {
  font-size: 14px;
}

.user-info i:first-child {
  font-size: 16px;
}

.header-btn i {
  margin-right: 4px;
}

/* 添加右键菜单样式 */
.context-menu {
  position: fixed;
  background: var(--bg-color);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  padding: 4px 0;
  z-index: 1000;
  min-width: 120px;
  border: 1px solid var(--border-color);
}

.context-menu-item {
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s;
  color: var(--text-color);
}

.context-menu-item:hover {
  background: var(--bg-color-secondary);
  color: var(--primary-color);
}

.sidebar.collapsed .logo {
  justify-content: center;
  padding: 16px 0;
}

.user-dropdown {
  position: relative;
}

.user-info i.rotate {
  transform: rotate(180deg);
}

.user-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 4px;
  background: var(--bg-color);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  min-width: 160px;
  z-index: 1000;
}

.user-menu-item {
  padding: 10px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s;
  color: var(--text-color);
}

.user-menu-item:hover {
  background: var(--bg-color-secondary);
  color: var(--primary-color);
}

.user-menu-item i {
  width: 16px;
  text-align: center;
}

/* 修改原有的用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.user-info i:last-child {
  transition: transform 0.3s;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: var(--bg-color);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  width: 90%;
  max-width: 400px;
  padding: 24px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--text-color);
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: var(--text-color-secondary);
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: var(--text-color);
}

.modal-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  color: var(--text-color);
}

.form-group input {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--bg-color);
  color: var(--text-color);
}

.form-group input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.2);
}

.form-tip {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.error-message,
.success-message {
  padding: 8px 12px;
  border-radius: var(--border-radius);
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.error-message {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  color: #ff4d4f;
}

.success-message {
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  color: #52c41a;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 8px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: transparent;
  border: 1px solid var(--border-color);
  color: var(--text-color);
}

.cancel-btn:hover {
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.submit-btn {
  background: var(--primary-color);
  border: none;
  color: white;
}

.submit-btn:hover {
  opacity: 0.9;
}

.submit-btn:disabled {
  background: var(--border-color);
  cursor: not-allowed;
  opacity: 1;
}
</style> 